import 'dart:convert';
import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:untitled/config.dart';
import 'package:untitled/routes.dart';
import 'package:untitled/scoped_model/AuthModel.dart';
import 'package:untitled/utils/common_toast.dart';
import 'package:untitled/utils/scopoed_model_helper.dart';

//公共网络请求类
class DioHttp {
  Dio _client;
  BuildContext context;

  static DioHttp of(BuildContext context) {
    return DioHttp._internal(context);
  }

  DioHttp._internal(BuildContext context) {
    if (_client == null || context != this.context) {
      this.context = context;
      var options = BaseOptions(
          baseUrl: Config.BaseUrl,
          connectTimeout: 1000 * 10,
          receiveTimeout: 1000 * 3,
          extra: {'context': context} //配置额外的参数

          );

      //拦截器
      Interceptor interceptor = InterceptorsWrapper(onResponse: (
        Response res,
        ResponseInterceptorHandler handler,
      ) {
        if (null == res) return res;
        var status = json.decode(res.toString())['status'];
        if(404 == status){
          CommonToast.showToast('接口地址错误!当前接口：${res.requestOptions.path}');
          return res;
        }
        //认为是token过期
        if(status.toString().startsWith('4')){
          // ignore: unnecessary_statements
          ScopedModelHelper.getModel<AuthModel>(context).logout();
          CommonToast.showToast('登录过期');
          Navigator.of(context).pushNamed(Routes.login);
          return res;
        }
        return res;
      });
      var client = Dio(options);
      client.interceptors.add(interceptor);
      _client = client;
    }
  }

//get请求
  Future<Response<Map<String, dynamic>>> get(String path,
      [Map<String, dynamic> params, String token]) async {
    var options = Options(headers: {'Authorization': token});
    return await _client.get(path, queryParameters: params, options: options);
  }

//post请求
  Future<Response<Map<String, dynamic>>> post(String path,
      [Map<String, dynamic> params, String token]) async {
    var options = Options(headers: {'Authorization': token});
    return await _client.post(path, queryParameters: params, options: options);
  }

//post请求上传表单数据
  Future<Response<Map<String, dynamic>>> postFormData(String path,
      [Map<String, dynamic> params, String token]) async {
    var options = Options(
        headers: {'Authorization': token}, contentType: 'multipart/form-data');
    return await _client.get(path, queryParameters: params, options: options);
  }
}
